package cn.iocoder.yudao.module.system.api.mail;

import cn.iocoder.yudao.module.system.api.mail.dto.MailSendCreateReqDTO;
import cn.iocoder.yudao.module.system.api.mail.dto.MailSendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.service.mail.MailSendService;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 邮件发送 API 实现类
 *
 * @author wangjingyi
 */
@Service
@Validated
public class MailSendApiImpl implements MailSendApi {

    @Resource
    private MailSendService mailSendService;
    //消费者注册邮箱模板
    private static final String TEMPLATE_CODE_MEMBER = "消费者注册邮箱模板";
    //使用redis +邮箱+模板编码
    private static final String redis_key = "member:user:create:verification:code";

    @Resource
    private  RedisTemplate<String, String> redisTemplate;

    @Override
    public Long sendSingleMailToAdmin(MailSendSingleToUserReqDTO reqDTO) {
        return mailSendService.sendSingleMailToAdmin(reqDTO.getMail(), reqDTO.getUserId(),
                reqDTO.getTemplateCode(), reqDTO.getTemplateParams());
    }

    @Override
    public Long sendSingleMailToMember(MailSendSingleToUserReqDTO reqDTO) {
        return mailSendService.sendSingleMailToMember(reqDTO.getMail(), reqDTO.getUserId(),
                reqDTO.getTemplateCode(), reqDTO.getTemplateParams());
    }

    /**
     * 注册时发送雅正码 Admin 用户
     * <p>
     * 固定模板编码 REGISTER_ADMIN
     *
     * @param reqDTO 发送请求
     * @return 发送日志编号
     */
    @Override
    public Long sendSingleMail(MailSendCreateReqDTO reqDTO) {

        this.setVerificationCodeValidityPeriod(reqDTO.getMail(),TEMPLATE_CODE_MEMBER ,3);
        reqDTO.setTemplateCode(TEMPLATE_CODE_MEMBER);
//        return mailSendService.sendSingleVerification(reqDTO);
        return null;
    }

    /**
     * 用户未登录时修改密码
     *
     * @param reqDTO 发送请求
     * @return 发送日志编号
     */
    @Override
    public Long sendSingleMailToMemberByMobile( String email,String mobile) {

        return mailSendService.sendMailCode(email,mobile);
    }

    public void setVerificationCodeValidityPeriod(String mail, String verificationCode, long timeout) {
        Validate.notNull(mail, "邮箱不能为空！");
        Validate.notNull(verificationCode, "短信验证码不能为空！", new Object[0]);
        Validate.notNull(timeout, "有效期（单位毫秒）不能为空！", new Object[0]);
        Validate.isTrue(timeout > 0L, "错误的有效期（单位毫秒）, 请检查!!", new Object[0]);
        this.redisTemplate.opsForValue().set(redis_key+mail, verificationCode, timeout, TimeUnit.SECONDS);
    }

}
